package com.mssh.login.filter;

import com.alibaba.fastjson.JSONObject;
import com.mssh.login.util.AesUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2023/09/20/14:06
 * @Description: 请求报文解密
 */
public class RequestDesEncryptWrappers extends HttpServletRequestWrapper {

    private Logger logger = LogManager.getLogger(RequestDesEncryptWrappers.class);

    private String aseKey;

    public RequestDesEncryptWrappers(HttpServletRequest request, String aseKey) {
        super(request);
        this.aseKey = aseKey;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        ServletInputStream servletInputStream = super.getInputStream();
        try {
            //请求报文解密
            return decryptReqData(servletInputStream, this.aseKey);
        } catch (Exception e) {
            logger.warn("请求报文解密异常：", e);
        }
        return servletInputStream;
    }

    /**
     * 请求报文解密
     * @param servletInputStream
     * @param aesKey
     * @return
     * @throws Exception
     */
    private ServletInputStream decryptReqData(ServletInputStream servletInputStream, String aesKey) throws Exception {
        //获取请求参数
        StringBuilder dataBuilder = new StringBuilder();
        String line = "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(servletInputStream));
        while ((line = reader.readLine()) != null) {
            dataBuilder.append(line);
        }
        String encryptReqData = dataBuilder.toString();
        if(!StringUtils.isEmpty(encryptReqData)) {
            JSONObject reqDataJSON = JSONObject.parseObject(encryptReqData);
            //请求报文解密
            String reqData = AesUtil.desEncryptWithKey(reqDataJSON.getString("encryptBody"), aesKey);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(reqData.getBytes(StandardCharsets.UTF_8));
            return new ServletInputStream() {
                @Override
                public int read() {
                    return byteArrayInputStream.read();
                }
                @Override
                public boolean isFinished() {
                    return false;
                }
                @Override
                public boolean isReady() {
                    return false;
                }
                @Override
                public void setReadListener(ReadListener listener) {
                }
            };
        }
        return servletInputStream;
    }

    /**
     * 获取请求头
     * @param request
     * @return
     */
    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        Locale.setDefault(Locale.ENGLISH);
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement().toLowerCase(Locale.ENGLISH);
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

}
